import {camelize, CSSProperties} from "vue";

/**
 * 防抖函数
 * @param callback
 * @param dealy
 * @param im
 */

export const debounce = (callback: Function, dealy: number = 200, im: boolean = false) => {
    let timeoutID: NodeJS.Timer | null = null;
    return function () {
        // 第一次触发时是否立即执行
        if (im && !timeoutID) callback.apply(debounce, arguments);
        if (timeoutID) clearTimeout(timeoutID);
        timeoutID = setTimeout(() => {
            // 借用外部第一个普通函数的this和arguments对象
            callback.apply(debounce, arguments);
            // 执行后将timeoutID置为null
            timeoutID = null
        }, dealy)
    }
};

export const useFormatDuring = (during: number) => {
    const s = Math.floor(during) % 60;
    during = Math.floor(during / 60);
    const i = during % 60;
    const ii = i < 10 ? `0${i}` : i;
    const ss = s < 10 ? `0${s}` : s;
    return ii + ':' + ss;
};
/**
 * 格式化数字
 * @param number
 */
export const useNumberFormat = (number: number): string | number => {
    if (number > 100000000) {
        return Number((number / 100000000).toFixed(1)) + ' 亿';
    }
    if (number > 10000000) {
        return Number((number / 10000000).toFixed(1)) + ' 千万';
    }
    if (number > 10000) {
        return Number((number / 10000).toFixed(1)) + ' 万';
    }
    return number;
};


export const getScrollContainer = (el: HTMLElement, isVertical?: boolean): Window | HTMLElement | undefined => {
    let parent: HTMLElement = el;
    while (parent) {
        if ([window, document, document.documentElement].includes(parent)) {
            return window;
        }
        if (isScroll(parent, isVertical)) return parent;
        parent = parent.parentNode as HTMLElement;
    }
    return parent;
};

export const isScroll = (el: HTMLElement, isVertical?: boolean): boolean => {
    const key = ({
        undefined: "overflow",
        true: "overflow-y",
        false: "overflow-x",
    } as const)[String(isVertical)]!;
    const overflow = getStyle(el, key);
    return ["scroll", "auto", "overlay"].some((s) => overflow.includes(s));
};

export const getStyle = (element: HTMLElement, styleName: keyof CSSProperties): string => {
    if (!element || !styleName) return "";
    let key = camelize(styleName);
    if (key === "float") key = "cssFloat";
    try {
        const style = (element.style as any)[key];
        if (style) return style;
        const computed: any = document.defaultView?.getComputedStyle(element, "");
        return computed ? computed[key] : "";
    } catch {
        return (element.style as any)[key];
    }
};
